<?php
namespace Admin;

    /*
     * To change this license header, choose License Headers in Project Properties.
     * To change this template file, choose Tools | Templates
     * and open the template in the editor.
     */

/**
 * Description of UsersController
 *
 * @author dung
 */
use AdminController,
    Sentry,
    View,
    Redirect,
    Input,
    Config,
    User,
    Category,
    Group,
    Lang,
    Str,
    DB,
    MyPaginator,
    Validator;

class UsersController extends AdminController
{

    /**
     * Show a list of all the users.
     *
     * @return View
     */
    public function getIndex()
    {
        $this->data = array('key' => '', 'withTrashed' => false, 'onlyTrashed' => false);
        //Grab all the users
        $users = Sentry::getUserProvider()->createModel();

        //include the deleted users?
        $this->data['onlyTrashed'] = Input::get('onlyTrashed', FALSE);
        $this->data['withTrashed'] = Input::get('withTrashed', FALSE);
        $this->data['groupId'] = Input::get('groupId', 0);
        $this->data['orderBy'] = Input::get('orderBy', 'create');
        $this->data['key'] = Input::get('key', '');
        $this->data['groups'] = Sentry::getGroupProvider()->findAll();
        $this->data['page'] = Input::get('page', 1);
        $count = $users->leftJoin('users_groups', 'users.id', '=', 'users_groups.user_id')
            ->where(function ($query) {
                if ($this->data['key'])
                    $query->where('users.username', 'like', '%' . $this->data['key'] . '%');
                if ($this->data['groupId'])
                    $query->where('users_groups.group_id', $this->data['groupId']);
            })->count(DB::raw("DISTINCT users.id"));
        $paginator = new MyPaginator($count, $this->data['page']);

        $this->data['users'] = $users
            ->select('users.id', 'users.username', 'users.created_at', 'users.activated', 'users.email', 'users.last_login')
            ->leftJoin('users_groups', 'users.id', '=', 'users_groups.user_id')
            ->where(function ($query) {
                if ($this->data['key'])
                    $query->where('users.username', 'like', '%' . $this->data['key'] . '%');
                if ($this->data['groupId'])
                    $query->where('users_groups.group_id', $this->data['groupId']);
            })
            ->groupBy('users.id')->take($paginator->pagesize)->skip($paginator->skip)->get();
        $this->data['paginator'] = $paginator;
        $data = $this->data;
        return View::make('backend/users/index', compact('data'));
    }

    /**
     * Form create user
     *
     * @return View
     */
    public function getCreate()
    {
        if (!Sentry::getUser()->hasAnyAccess(['user', 'user.create']))
            return View::make('backend/notallow');
        // get all the available groups
        $data['Groups'] = Sentry::getGroupProvider()->findAll();

        // get all available permissions
        $data['Permissions'] = Config::get('permissions');
        $this->encodeAllPermissions($data['Permissions']);

        //selectec permissions
        $data['selectedPermissions'] = Input::old('permissions', array());
        $this->encodePermissions($data['selectedPermissions']);


        return View::make('backend/users/create', compact('data'));
    }

    /**
     * create user processing
     *
     * @return Redirect
     */
    public function postCreate()
    {
        if (!Sentry::getUser()->hasAnyAccess(['user', 'user.create']))
            return View::make('backend/notallow');
        $data = Input::get('data');

        $user = new User();

        $validation = $user->validate($data['User'], array('create' => true));

        if ($validation->fails())
            return Redirect::back()->withInput()->withErrors($validation);
        try {
            $permissions = Input::get('permissions', array());
            $this->decodePermissions($permissions);
            app('request')->request->set('permissions', $permissions);

            unset($data['User']['password_confirm']);
            $data['User']['permissions'] = $permissions;
            //if create user success
            if ($user = Sentry::getUserProvider()->create($data['User'])) {
                // assign the selected groups to this user
                foreach (isset($data['Groups']) ? $data['Groups'] : array() as $groupId) {

                    $group = Sentry::getGroupProvider()->findById($groupId);

                    $user->addGroup($group);
                }
                //prepare the success message
                $success = Lang::get('admin/user/message.success.create');

                return Redirect::route('update/user', $user->id)->with('success', $success);
            }

            //prepare the error message
            $error = Lang::get('admin/user/message.error.create');

            //Redirect to the user creation page
            return Redirect::route('create/user')->with('error', $error);
        } catch (LoginRequiredException $e) {
            $error = Lang::get('admin/user/message.user_login_required');
        } catch (PasswordRequiredException $e) {
            $error = Lang::get('admin/user/message.user_password_required');
        } catch (UserExistsException $e) {
            $error = Lang::get('admin/user/message.user_exists');
        }
        return Redirect::route('create/user')->withInput()->with('error', $error);
    }

    /**
     * Show form edit user
     *
     * @param Integer $id
     *
     * @return View
     */
    public function getEdit($id = null)
    {
        if (!Sentry::getUser()->hasAnyAccess(['user', 'user.edit']))
            return View::make('backend/notallow');
        try {
            // Get user  information
            $data['User'] = Sentry::getUserProvider()->findById($id);
            // Get user's groups
            $data['userGroups'] = $data['User']->groups()->lists('name', 'group_id');
            // Get user permissions
//            $userPermission = array_merge(Input::old('permissions', array('superuser' => -1)), $data['User']->getPermissions());
            $permissions = array_merge(array('superuser' => -1), $data['User']->getPermissions());

            $this->encodePermissions($permissions);
            $data['User']['permissions'] = $permissions;
            // Get user categories permissions
            $data['catPermissions']['Phân quyền danh mục'] = array();
            foreach (Category::where('status', 'on')->where('parent_id', 0)->get() as $cat) {
                $data['catPermissions']['Phân quyền danh mục'][] = array(
                    'permission' => 'category.c' . $cat->id,
                    'label' => $cat->title,
                    'can_inherit' => 1,
                    'type' => 'cat'
                );
            }
            $this->encodeAllPermissions($data['catPermissions'], true);

            // get list of all available groups
            $data['Groups'] = Sentry::getGroupProvider()->findAll();
            //get all available permissions
            $data['Permissions'] = Config::get('permissions');
            $this->encodeAllPermissions($data['Permissions']);
        } catch (UserNotFoundException $e) {
            $error = Lang::get('admin/users/message.user_not_found', compact('id'));

            return Redirect::route('users')->with('error', $error);
        }

        return View::make('backend/users/edit', compact('data'));
    }

    /**
     * update user processing
     *
     * @param integer $id
     *
     * @return Redirect
     */
    public function postEdit($id = null)
    {
        if (!Sentry::getUser()->hasAnyAccess(['user', 'user.edit']))
            return View::make('backend/notallow');
        $data = Input::get('data');
        try {
            $user = Sentry::getUserProvider()->findById($id);
        } catch (UserNotFoundException $e) {
            // prepare the error message
            $error = Lang::get('admin/user/message.user_not_found', compact('id'));

            // Redirect to the user management page
            Redirect::route('users')->with('error', $error);
        }

        if ($data['User']['password']) {
//            $validator = $user->validator($data['User'], array('notEmail' => true));
//            if ($validator->fails())
//                return Redirect::back()->withInput()->withErrors($validator);
            unset($data['User']['password_confirm']);
        } else {
            unset($data['User']['password']);
            unset($data['User']['password_confirm']);
        }

        $uPermissions = isset($data['User']['permissions']) ? $data['User']['permissions'] : array();

        $cPermissions = isset($data['Permissions']) ? $data['Permissions'] : array();

        $this->decodePermissions($uPermissions);
        $this->decodePermissions($cPermissions);

        $data['User']['permissions'] = array_merge($uPermissions, $cPermissions);

        // get all the available user's groups
        $userGroups = $user->groups()->lists('group_id', 'group_id');

        // get all groups selected
        $selectedGroups = isset($data['Groups']) ? $data['Groups'] : array();
        // Groups comparison between the groups the user currently
        // have and the groups the user wish to have.
        $groupsToAdd = array_diff($selectedGroups, $userGroups);
        $groupsToRemove = array_diff($userGroups, $selectedGroups);

        // Assign the user to groups
        foreach ($groupsToAdd as $groupId) {
            $group = Sentry::getGroupProvider()->findById($groupId);

            $user->addGroup($group);
        }

        // Remove the user from groups
        foreach ($groupsToRemove as $groupId) {
            $group = Sentry::getGroupProvider()->findById($groupId);

            $user->removeGroup($group);
        }

        $user->fill($data['User']);

        if ($user->save()) {
            $success = Lang::get('admin/user/message.success.update');

            return Redirect::route('update/user', $id)->with('success', $success);
        }
        return Redirect::route('update/user', $id);
    }

    /**
     * Delete the given user.
     *
     * @param  int $id
     * @return Redirect
     */
    public function getDelete($id = null)
    {
        if (!Sentry::getUser()->hasAnyAccess(['user', 'user.delete']))
            return View::make('backend/notallow');

        try {
            // Get user information
            $user = Sentry::getUserProvider()->findById($id);

            // Check if we are not trying to delete ourselves
            if ($user->id === Sentry::getId()) {
                // Prepare the error message
                $error = Lang::get('admin/users/message.error.delete');

                // Redirect to the user management page
                return Redirect::route('users')->with('error', $error);
            }

            // Do we have permission to delete this user?
            if ($user->isSuperUser() and !Sentry::getUser()->isSuperUser()) {
                // Redirect to the user management page
                return Redirect::route('users')->with('error', 'Insufficient permissions!');
            }

            // Delete the user
            $user->delete();

            // Prepare the success message
            $success = Lang::get('admin/users/message.success.delete');

            // Redirect to the user management page
            return Redirect::route('users')->with('success', $success);
        } catch (UserNotFoundException $e) {
            // Prepare the error message
            $error = Lang::get('admin/users/message.user_not_found', compact('id'));

            // Redirect to the user management page
            return Redirect::route('users')->with('error', $error);
        }
    }

    /**
     * Restore a deleted user.
     *
     * @param  int $id
     * @return Redirect
     */
    public function getRestore($id = null)
    {
        if (!Sentry::getUser()->hasAnyAccess(['user', 'user.delete']))
            return View::make('backend/notallow');

        try {
            // Get user information
            $user = Sentry::getUserProvider()->createModel()->withTrashed()->find($id);

            // Restore the user
            $user->restore();

            // Prepare the success message
            $success = Lang::get('admin/users/message.success.restored');

            // Redirect to the user management page
            return Redirect::route('users')->with('success', $success);
        } catch (UserNotFoundException $e) {
            // Prepare the error message
            $error = Lang::get('admin/users/message.user_not_found', compact('id'));

            // Redirect to the user management page
            return Redirect::route('users')->with('error', $error);
        }
    }

}
